const fs = require('fs');
const path = require('path');
const Router = require('koa-router');
const router = new Router();
module.exports = loadRouters;

/**
 * @function loadDirectory 目录加载器, 按目录层次组装并加载
 * @param {Object} app app实例
 * @param {String} directory 目录路径
 * @param {Array} afterRouters 后置路由文件
 * @return {undefined} 没有返回值
 */
function loadRouters(app, directory, afterRouters = []) {
  if (!app.router){
      app.router = router;
  }
  if (!fs.existsSync(directory)) {
    return;
  }
  const afterRoutersPath = [];
  fs.readdirSync(directory).forEach((file, index) => {
    let fullPath = path.join(directory + '/' + file);

    // 跳过后置路由
    if (afterRouters.length && file.endsWith('.js') && afterRouters.indexOf(file.replace('.js', '')) > -1) {
      afterRoutersPath.push(fullPath);
      return;
    }

    let stat = fs.statSync(fullPath);
    if (stat.isDirectory()) {
      loadRouters(app, fullPath, afterRouters);
    } else if (file.endsWith('.js')) {
      require(fullPath)(app);
    }
  });

  // 将后置文件放到最后
  afterRoutersPath.forEach(item => {
    require(item)(app);
  });

  // 使用routers
  app.use(router.routes());
  app.use(router.allowedMethods());
}
